package com.hexacta.hrs;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.orm.hibernate3.LocalSessionFactoryBean;

import com.hexacta.hrs.test.data.TestDataCreator;

/**
 * Database Fixture is a delegate object responsible for initializing the
 * database schema and populate it with the test data. It takes this
 * responsibility from the test case, and so simplifies it.
 * 
 * @author tpollak
 */
public class DatabaseFixture implements ApplicationContextAware {
    private ApplicationContext applicationContext;

    private final Map<String, Object> testDataContext = new HashMap<String, Object>();

    private TestDataCreator txAllTestDataCreator;

    public Map<String, Object> getTestDataContext() {
        return this.testDataContext;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Resource
    public void setTxAllTestDataCreator(TestDataCreator txAllTestDataCreator) {
        this.txAllTestDataCreator = txAllTestDataCreator;
    }

    public void setUp() throws Exception {
        this.restoreEmptyDatabase();
        this.loadTestData();
    }

    public void tearDown() {
        // Nothing to do
    }

    private TestDataCreator getTxAllTestDataCreator() {
        return this.txAllTestDataCreator;
    }

    private void loadTestData() {
        this.getTxAllTestDataCreator().createTestData(this.testDataContext);
    }

    private void restoreEmptyDatabase() {
        LocalSessionFactoryBean sessionFactory = (LocalSessionFactoryBean) this.applicationContext
                .getBean("&sessionFactory");
        sessionFactory.dropDatabaseSchema();
        sessionFactory.createDatabaseSchema();
    }
}
